package com.zzyl.nursing.controller.member;

import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@RestController
@RequestMapping(value = {
        "/member/reservation",        // 你的原正确路径（单数）
        "/member/reservations",       // 兼容：小程序可能的复数路径
        "/api/member/reservation",    // 兼容：小程序可能加的/api前缀
        "/api/member/reservations"    // 兼容：小程序可能的/api+复数路径
})
@Api(tags = "小程序-参观预约接口")
public class ReservationController {

    @Autowired
    private IReservationService reservationService;

    @ApiOperation("查询当天取消预约次数")
    @GetMapping(value = {
            "/cancelled-count",  // 你的原正确路径（横杠）
            "/cancelledCount",   // 兼容：小程序可能的驼峰路径
            "/cancelCount"       // 兼容：小程序可能的简写路径
    })
    public AjaxResult getCancelledCount() {
        Long userId = UserThreadLocal.get();
        if (userId == null) {
            return AjaxResult.error("请先登录");
        }
        try {
            Integer count = reservationService.getCancelledCountToday(userId);
            return AjaxResult.success(count);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("查询时间段剩余预约次数")
    @GetMapping(value = {"/countByTime", "/countbytime", "/count-by-time"})
    public AjaxResult getCountByTime(
            @RequestParam Long time) { // 接收 long 类型时间戳
        try {
            // 时间戳转 Date（处理时区，避免偏移）
            Date queryDate = new Date(time);
            List<Reservation> list = reservationService.getRemainingCountByTime(queryDate);
            return AjaxResult.success(list);
        } catch (Exception e) {
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("新增预约")
    @PostMapping(value = {
            "",          // 你的原正确路径（空，对应 /member/reservation）
            "/"          // 兼容：小程序可能带的斜杠（对应 /member/reservation/）
    })
    public AjaxResult create(@RequestBody Reservation reservation) {
        Long userId = UserThreadLocal.get();
        if (userId == null) {
            return AjaxResult.error("请先登录");
        }
        try {
            boolean success = reservationService.createReservation(reservation, userId);
            return success ? AjaxResult.success("预约成功") : AjaxResult.error("预约失败");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("分页查询预约记录")
    @GetMapping(value = {
            "/page",   // 你的原正确路径
            "/list"    // 兼容：小程序可能用的/list路径
    })
    public AjaxResult page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Reservation reservation) {
        Long userId = UserThreadLocal.get();
        if (userId == null) {
            return AjaxResult.error("请先登录");
        }
        try {
            TableDataInfo tableData = reservationService.getUserReservationPage(pageNum, pageSize, userId, reservation);
            return AjaxResult.success(tableData); // 此时data为{total, rows}
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("取消预约")
    @PutMapping(value = {
            "/{id}/cancel",              // 你的原正确路径
            "/{id}/cancelReservation"    // 兼容：小程序可能的完整路径
    })
    public AjaxResult cancel(@PathVariable Long id) {
        Long userId = UserThreadLocal.get();
        if (userId == null) {
            return AjaxResult.error("请先登录");
        }
        try {
            boolean success = reservationService.cancelReservation(id, userId);
            return success ? AjaxResult.success("取消成功") : AjaxResult.error("取消失败");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}